// pages/profile/profile-info/profile-shipping-address/profile-shipping-address.js
import WxValidate from '../../../../utils/WxValidate'

const app = getApp()
const constant = require("../../../../constant.js")
const storage = require("../../../../utils/storage.js")
const address = require('../../../../utils/city.js')


var animation
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuType: 0,
    begin: null,
    status: 1,
    end: null,
    isVisible: false,
    animationData: {},
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    province: '',
    city: '',
    area: '',
    isChangeCity: false,
    disabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.initValidate();

    // 初始化动画变量
    var animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation;
    // 默认联动显示北京
    var id = address.provinces[0].id
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    let unionid = wx.getStorageSync(storage.keys.unionid);

    wx.request({
      url: constant.api(app.globalData.pord).url + '/profile/shipping-address?unionid=' + unionid,
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        if (res.data.code == "0") {
          that.setData({
            userProfile: res.data.data.shippingAddress
          });
        } else {
          wx.showToast({
            title: res.data.message ? res.data.message : '请求失败',
            icon: 'none',
            duration: 3000,
            mask: true
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '加载数据失败',
          icon: 'none',
          duration: 3000,
          mask: true
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  showModal(message) {
    wx.showModal({
      content: message.msg,
      showCancel: false,
    })
  },

  initValidate: function() {
    // 验证字段的规则
    const rules = {
      name: {
        required: true,
      },
      mobile: {
        required: true,
        tel: true,
      },
      region: {
        required: true,
      },
      address: {
        required: true,
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      name: {
        required: '请输入联系人',
      },
      mobile: {
        required: '请输入手机号',
        tel: '请输入正确的手机号',
      },
      region: {
        required: '请选择所在地区',
      },
      textarea: {
        required: '请输入详细地址',
      }
    }

    this.WxValidate = new WxValidate(rules, messages)
  },

  // 点击所在地区弹出选择框
  selectDistrict: function (e) {
    var that = this
    if (that.data.addressMenuIsShow) {
      return
    }
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    var that = this
    if (isShow) {
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(40 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
    this.setData({
      isChangeCity: false,
    })
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var value = that.data.value
    that.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var areaInfo = that.data.provinces[value[0]].name + ',' + that.data.citys[value[1]].name + ',' + that.data.areas[value[2]].name;
    that.setData({
      areaInfo: areaInfo,
      isChangeCity: true
    })
  },
  hideCitySelected: function (e) {
    this.startAddressAnimation(false)
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
    this.setData({
      isChangeCity: true,
    })
  },

  formSubmit: function (e) {
    let unionid = wx.getStorageSync(storage.keys.unionid);

    const params = e.detail.value
    let that = this;

    if (!that.WxValidate.checkForm(params)) {
      const error = that.WxValidate.errorList[0]
      that.showModal(error)
      return false
    } else {
      that.setData({
        disabled: true
      })
      wx.request({
        url: constant.api(app.globalData.pord).url + '/profile/shipping-address?unionid=' + unionid + '&name=' + e.detail.value.name + '&mobile=' + e.detail.value.mobile + '&region=' + e.detail.value.region + '&address=' + e.detail.value.address + '&_method=PATCH',
        method: 'POST',
        dataType: 'json',
        responseType: 'text',
        success: function (res) {
          if (res.data.code == "0") {
            wx.navigateBack({
              delta: 1
            });
          } else {
            that.setData({
              disabled: false
            })
            wx.showToast({
              title: res.data.message ? res.data.message : '请求失败',
              icon: 'none',
              duration: 3000,
              mask: true
            })
          }
        },
        fail: function (res) {
          that.setData({
            disabled: false
          })
          that.showModal(res)
        }
      })
    }
  }
})